<script setup name="Subcontracting">
import { Search } from '@element-plus/icons-vue'
import {
  GetListAPI,
  AddDataAPI,
  EditDataAPI,
  DelDataAPI,
  GetDetailAPI,
  DeleteReviewAPI,
  SubmitReviewAPI,
  ToExamineAPI
} from '@/api/order/sale/sample'
import Form from './form.vue'
const { proxy } = getCurrentInstance()
// 封装 方法 字典查询
const {
  customer_level, // 等级
  customer_affiliated_organization, //所属机构
  subcontracting_order_status //单据状态
} = proxy.useDict('customer_level', 'customer_affiliated_organization', 'subcontracting_order_status')

//

const formRef = ref(null)

// 新增弹窗状态
const addIsShow = ref(false)

// 审核弹窗状态
const examineIsShow = ref(false)

// 标题
const title = ref('新增')

// 保存加载状态
const Btnloading = ref(false)

// 表格加载状态
const loading = ref(false)

// 表格数据
const TableData = ref([])

// 列表总数量
const total = ref(0)

// 是否禁用删除
const DelDisabled = ref(false)

// 是否禁用 单选
const ExamineDisabled = ref(false)

//
const Ids = ref([])
const rows = ref([])
let id = ''
// 查询条件
const SelectList = ref([
  { type: '日期范围' },
  { label: '样品订单号', model: 'sampleOrderNum', type: '输入框', placeholder: '请输入委外订单号' },
  { label: '物料编码', model: 'materialCode', type: '输入框', placeholder: '请输入物料编码' }
])

// 校验枚举
const checkAge = (rule, value, callback) => {
  // console.log(!/[A-Z]/.test(value))
  if (!(/[A-Z]/.test(value) && value.length === 4)) return callback(new Error('只能为4位大写字母'))
  callback()
}

const rules = reactive({
  affiliatedOrganization: [{ required: true, message: '请选择所属机构', trigger: 'change' }],
  customerName: [{ required: true, message: '请填写加工商名称', trigger: 'blur' }],
  customerAbbreviation: [
    { required: true, message: '请填写加工商简称', trigger: 'blur' },
    { validator: checkAge, trigger: 'blur' }
  ],
  customerLevel: [{ required: true, message: '请选择加工商等级', trigger: 'change' }],
  customerAddress: [{ required: true, message: '请选择加工商地址', trigger: 'change' }]
  // contactsBy: [{ required: true, message: '请填写联系人', trigger: 'blur' }],
  // contactsInformation: [{ required: true, message: '请填写联系方式', trigger: 'blur' }],
  // ascriptionBy: [{ required: true, message: '请选择归属人', trigger: 'change' }]
  // businessLicense: [{ required: true, message: '请上传开票信息', trigger: 'change' }],
  // invoicingInformation: [{ required: true, message: '请上传营业执照', trigger: 'change' }]
})

// 新增字段
const ruleForm = ref({})

// 查询条件
const query = reactive({
  pageNum: 1,
  pageSize: 10
})
/**
 * 弹窗 SAT--------------------
 */

const add = () => {
  title.value = '新增'
  addIsShow.value = true
}

const edit = async id => {
  try {
    proxy.$modal.loading('请稍候...')
    title.value = '修改'
    const res = await GetDetailAPI(id)
    ruleForm.value = res.data
    addIsShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

const examine = async () => {
  if (rows.value[0].sampleStatus != 2 && rows.value[0].sampleStatus != 3)
    return proxy.warningMsg('此操作仅为待审核和审核中状态可用')

  try {
    proxy.$modal.loading('请稍候...')
    title.value = '审核'
    const res = await GetDetailAPI(Ids.value[0])
    ruleForm.value = res.data
    examineIsShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 查看
const dxamine = async val => {
  try {
    proxy.$modal.loading('请稍候...')
    title.value = '查看'
    rows.value = [val]
    const res = await GetDetailAPI(val.id)
    if (res.code !== 200) return
    ruleForm.value = res.data
    examineIsShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

/**
 * 弹窗 END--------------------
 */

// 列表选中 及 判断是否禁用删除 || 修改
const handleSelectionChange = selection => {
  rows.value = selection
  Ids.value = selection.map(item => item.id)
  DelDisabled.value = !selection.length
  selection.length <= 0 || selection.length > 1 ? (ExamineDisabled.value = true) : (ExamineDisabled.value = false)
}
handleSelectionChange([])

// 新增
const addSub = async () => {
  try {
    const isif = await formRef.value.submit()
    if (!isif) return
    Btnloading.value = true
    await AddDataAPI(isif)
    addClose()
    getList()
    proxy.successMsg('新增成功')
  } catch {
  } finally {
    Btnloading.value = false
  }
}

// 修改
const editSub = async () => {
  const isif = await formRef.value.submit()
  if (!isif) return
  try {
    Btnloading.value = true
    await EditDataAPI(isif)
    addClose()
    getList()
    proxy.successMsg('修改成功')
  } catch {
  } finally {
    // console.log('aa')
    Btnloading.value = false
  }
}

// 删除
const remove = async val => {
  const MesBox = await proxy.DelMessageBox()
  if (!MesBox) return
  await DelDataAPI(val ? val : Ids.value.join(','))
  getList()
  proxy.successMsg('删除成功')
}

// 撤销审核
const revoke = async () => {
  if (rows.value[0].sampleStatus != 2) return proxy.warningMsg('此操作仅状态为待审核数据')
  const MesBox = await proxy.RevokeMessageBox()
  if (!MesBox) return
  await DeleteReviewAPI(Ids.value.join(','))
  getList()
  proxy.successMsg('撤销成功')
}

// 提交审核
const subExamine = async () => {
  const is = rows.value.every(t => [1].includes(t.sampleStatus))
  if (!is) return proxy.warningMsg('只有待提交的数据可操作!')
  const MesBox = await proxy.ExamineMessageBox()
  if (!MesBox) return
  const res = await SubmitReviewAPI({ idStr: Ids.value.join(',') })
  if (res.code !== 200) return
  getList()
  proxy.successMsg('操作成功')
}

/**
 * 批量审核
 */
const allExamine = async () => {
  const is = rows.value.every(t => [2, 3].includes(t.sampleStatus))
  if (!is) return proxy.warningMsg('只有待审核和审核中的数据可操作!')
  const num = rows.value.length
  const MesBox = await proxy.FreezMessageBox1(`共${num}条审核订单`)
  if (MesBox) {
    await ToExamineAPI({
      idStr: Ids.value.join(','),
      isAdopt: '1'
    })
    getList()
  } else {
    await ToExamineAPI({
      idStr: Ids.value.join(','),
      isAdopt: '2'
    })
    getList()
  }
}

// 审核同意 || 不同意  （同意1 不同意 2
const yesAndNo = async val => {
  const isif = await formRef.value.submit()
  if (!isif) return
  try {
    Btnloading.value = true
    const form = {
      reviewComments: isif.reviewComments,
      idStr: Ids.value[0],
      isAdopt: val
    }
    await ToExamineAPI(form)
    examineIsShow.value = false
    getList()
    proxy.successMsg('操作成功')
  } catch {
  } finally {
    Btnloading.value = false
  }
}

//  弹窗关闭时
const addClose = () => {
  addIsShow.value = false
  examineIsShow.value = false
  ruleForm.value = {}
}

const selectSubmit = val => {
  for (let key in val) {
    query[key] = val[key]
  }
  getList()
}
// 获取列表
const getList = async () => {
  loading.value = true
  try {
    const res = await GetListAPI(query)
    TableData.value = res.rows
    total.value = res.total
  } catch (error) {
    loading.value = false
  } finally {
    loading.value = false
  }
}
getList()
</script>

<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <SelectForm :SelectForm="SelectList" @selectSubmit="selectSubmit" />
    <el-card class="box-card">
      <el-button type="primary" v-hasPermi="['order:sale:sample:add']" @click="add">添加</el-button>
      <el-button
        type="warning"
        v-hasPermi="['order:sale:sample:subExamine']"
        :disabled="DelDisabled"
        @click="subExamine"
        >提交审核</el-button
      >
      <el-button type="warning" v-hasPermi="['order:sale:sample:examine']" :disabled="DelDisabled" @click="allExamine"
        >批量审核</el-button
      >
      <el-button type="warning" v-hasPermi="['order:sale:sample:examine']" :disabled="ExamineDisabled" @click="examine"
        >审核</el-button
      >
      <el-button type="primary" v-hasPermi="['order:sale:sample:revoke']" :disabled="ExamineDisabled" @click="revoke"
        >撤销审核</el-button
      >
      <!-- <el-button type="success" :disabled="ExamineDisabled" @click="closing(false)">删除</el-button> -->
      <el-button type="danger" v-hasPermi="['order:sale:sample:remove']" :disabled="DelDisabled" @click="remove(false)"
        >删除</el-button
      >
      <!-- <el-button type="info" @click="importFn">导入</el-button>
      <el-button type="info" @click="exportFn">导出</el-button> -->
      <!-- 表格数据 -->
      <el-table
        class="tableClass"
        v-loading="loading"
        stripe
        border
        :data="TableData"
        @selection-change="handleSelectionChange"
        height="500px"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="序号" width="70" type="index" />
        <el-table-column label="样品订单号" prop="sampleOrderNum" width="150" />
        <el-table-column label="样品状态" align="center" width="120">
          <template #default="scope">
            <p-tag bgc="#006cb6" text="待提交" v-if="scope.row.sampleStatus == 1" />
            <p-tag bgc="#fbc82f" text="待审核" v-else-if="scope.row.sampleStatus == 2" />
            <p-tag bgc="#f28e16" text="审核中" v-else-if="scope.row.sampleStatus == 3" />
            <p-tag bgc="#43b244" text="已完成" v-else-if="scope.row.sampleStatus == 4" />
            <p-tag bgc="#ff0000" text="未通过" v-else-if="scope.row.sampleStatus == 5" />
            <p-tag bgc="#593fd7" text="进行中" v-else />
          </template>
        </el-table-column>
        <el-table-column label="物料名称" prop="materialName" width="150" />
        <el-table-column label="物料编码" prop="materialCode" width="150" />
        <el-table-column label="物料规格" prop="materialSpec" width="150" />
        <el-table-column label="规格型号" prop="specType" width="150" />
        <el-table-column label="打样数量" prop="proofingWeight" width="150" />
        <el-table-column label="质量标准" prop="qualityStandardDict" width="150" />
        <el-table-column label="交货日期" prop="deliveryDate" width="150" />
        <el-table-column label="需求部门" prop="demandDepartmentDict" width="150" />
        <el-table-column label="备注" align="center" prop="remark" width="150" :show-overflow-tooltip="true" />
        <el-table-column label="创建人" prop="createBy" width="150" />
        <el-table-column label="创建时间" prop="createTime" width="180" />
        <el-table-column label="审核人" prop="reviewBy" width="150" />
        <el-table-column label="审核时间" prop="reviewTime" width="180" />
        <el-table-column label="操作" align="center" width="160" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <div>
              <el-link
                type="primary"
                v-hasPermi="['order:sale:sample:edit']"
                v-show="scope.row.sampleStatus == 1 || scope.row.sampleStatus == 5"
                text="修改"
                @click="edit(scope.row.id)"
              />
              <el-link
                type="primary"
                text="删除"
                v-hasPermi="['order:sale:sample:remove']"
                @click="remove(scope.row.id)"
              />
              <el-link
                type="primary"
                text="查看"
                v-hasPermi="['order:sale:sample:query']"
                @click="dxamine(scope.row)"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 新增弹窗 -->
    <p-XiaoheDialog :dialogVisible="addIsShow" :title="title" @close="addClose" width="50%">
      <template #body>
        <Form ref="formRef" :title="title" :disabled="title == '查看'" :data="ruleForm" @close="addClose" />
        <div style="width: 100%" v-if="title == '新增' || title == '修改'">
          <div class="Btn">
            <el-button type="primary" :loading="Btnloading" @click="title == '新增' ? addSub() : editSub()"
              >保存</el-button
            >
            <el-button type="inof" @click="addClose">取消</el-button>
          </div>
        </div>
      </template>
    </p-XiaoheDialog>

    <!-- 审核 -->
    <p-XiaoheDialog :dialogVisible="examineIsShow" :title="title" @close="addClose" width="50%">
      <template #body>
        <AuditHistory :auditDoc="rows[0].sampleOrderNum" perms="order:sample:review">
          <template #body>
            <Form
              ref="formRef"
              :title="title"
              :disabled="title == '查看' || title == '审核'"
              :data="ruleForm"
              @close="addClose"
            />
          </template>
        </AuditHistory>
        <div>
          <div class="Btn" v-if="title == '审核'">
            <el-button type="danger" :loading="Btnloading" @click="yesAndNo(2)">不同意</el-button>
            <el-button type="success" :loading="Btnloading" @click="yesAndNo(1)">同意</el-button>
            <el-button type="inof" @click="addClose">取消</el-button>
          </div>
        </div>
      </template>
    </p-XiaoheDialog>
  </div>
</template>

<style lang="scss" scoped></style>
